﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tauren.Business.Entity.Enum;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Globals;

namespace Tauren.Business.DLL.FieldsDLL
{
    public class FieldBusiness : Base.BaseDLL, IFieldBusiness
    {
        public FieldBusiness(IConnectionDLLBase _dLLBase) : base(_dLLBase)
        {
        }

        public bool CreateField(Fields field)
        {
            string types = ConvertFieldType(field.FieldType.Value, field.FieldLength);
            return dbConnection.Execute($"ALTER TABLE  {field.TableCode} ADD {field.FieldCode} {types}") >= 0;
        }

        public bool EditField(Fields field)
        {
            string types = ConvertFieldType(field.FieldType.Value, field.FieldLength);
            return dbConnection.Execute($"ALTER TABLE  {field.TableCode} MODIFY {field.FieldCode} {types}") >= 0;
        }

        public decimal GetSeq()
        {
            Fields fields = this.dbConnection.QueryFirstOrDefault<Fields>("SELECT * FROM fields WHERE havedelete=0  ORDER BY autoid DESC LIMIT 0,1");
            if (fields is null) return 1;
            else return (fields.Sequence is null ? 1 : fields.Sequence.Value + 1);
        }

        public bool IsPermissionCodeRepeat(long AutoId, string Code, string tableCode)
        {
            string sql = $"SELECT * FROM fields WHERE fieldcode='{Code}' and tablecode='{tableCode}'";
            if (AutoId != 0)
            {
                sql = $"{sql} AND autoid != {AutoId}";
            }
            return dbConnection.Query<TableInfo>(sql).Any();
        }

        public List<PageFieldsTable> Pages(QueryModel queryModel, out long Total)
        {
            Total = 0;
            string where = "";
            if (!string.IsNullOrEmpty(queryModel.KeyWord))
            {
                where += $"   AND f.fieldcode  LIKE '%{queryModel.KeyWord}%' OR f.fieldenname LIKE '%{queryModel.KeyWord}%' OR f.fieldenname LIKE '%{queryModel.KeyWord}%' ";
            }
            if (string.IsNullOrEmpty(queryModel.SortField))
            {
                queryModel.SortField = "autoId";
                queryModel.IsAsc = true;
            }
            else
            {
                queryModel.SortField = queryModel.SortField.ToLower().Replace("dic_", "").Replace("dic", "").Trim();
            }
            if (queryModel.ExceptDataField.Any())
            {
                queryModel.ExceptDataField.ForEach(o =>
                {
                    if (!string.IsNullOrEmpty(o.Value + ""))
                        where += $" AND f.{o.Label}!='{o.Value}'";
                });
            }
            if (queryModel.paramters.Any())
            {
                queryModel.paramters.ForEach(o =>
                {
                    if (!string.IsNullOrEmpty(o.Value + ""))
                        where += $" AND f.{o.Label}='{o.Value}'";
                });
            }
            if (!queryModel.UseDisabledData)
            {
                where += $" AND f.enable=1  ";
            }
            string asc = queryModel.IsAsc ? "ASC" : "DESC";
            queryModel.Page = queryModel.Page == 0 ? 1 : queryModel.Page;
            StringBuilder sql = new StringBuilder();
            sql.Append(@$"select count(f.autoid) from fields f left join tableinfo t on t.tablecode =f.tablecode WHERE f.havedelete !=1
                        {where}  ;");
            sql.Append(@$"select
	                            f.autoid,
	                            f.tablecode,
	                            f.fieldcode ,
	                            f.fieldname ,
	                            f.fieldenname,
	                            f.controlstype,
                                f.controlsouces,
	                            f.fieldtype,
                                f.selecttype,
                                f.defaultvalue,
                                f.fieldlength,
                                f.isrequired,
                                f.isinlay,
                                f.precisions,
                                f.sequence,
	                            f.enable,
	                            f.creator,
	                            f.creatdate,
	                            case
		                            when '{Global.Language}' = 'zh-cn' then t.cnname
		                            else t.enname
	                            end tablename 
                        FROM fields f left join tableinfo t on  t.tablecode =f.tablecode WHERE f.havedelete !=1
                        {where}  ORDER BY {queryModel.SortField} {asc} LIMIT {(queryModel.Page - 1) * queryModel.PageSize},{queryModel.PageSize} ;");
            using (var reader = dbConnection.QueryMultiple(sql.ToString()))
            {
                Total = reader.ReadFirstOrDefault<int>();
                List<PageFieldsTable> pageModules = reader.Read<PageFieldsTable>().ToList();
                long RowNo = ((queryModel.Page == 0 ? 1 : queryModel.Page) - 1) * queryModel.PageSize + 1;
                pageModules.ForEach(o =>
                {
                    o.RowNo = RowNo;
                    RowNo++;
                });
                return pageModules;
            }
        }
        private string ConvertFieldType(int fdype, int fileLength)
        {
            FieldType fieldType = (FieldType)fdype;
            string types = "";
            switch (fieldType)
            {
                case FieldType.varchar:
                    types = $" varchar({(fileLength > 0 ? fileLength : 200)}) NULL ";
                    break;
                case FieldType.bigint:
                    types = " BIGINT NULL ";
                    break;
                case FieldType.doubled:
                    types = " DOUBLE NULL ";
                    break;
                case FieldType.date:
                    types = " DATE NULL ";
                    break;
                case FieldType.year:
                    types = $" varchar({(fileLength > 0 ? fileLength:200)}) NULL ";
                    break;
                case FieldType.month:
                    types = $" varchar({(fileLength > 0 ? fileLength : 200)}) NULL ";
                    break;
                case FieldType.day:
                    types = $" varchar({(fileLength > 0 ? fileLength : 200)}) NULL ";
                    break;
                case FieldType.datetime:
                    types = " DATETIME NULL ";
                    break;
                case FieldType.bit:
                    types = " BIT NULL ";
                    break;
                default:
                    break;
            }
            return types;
        }
    }
}
